package com.chapter04;

import com.bdqn.util.JDBCUtils;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;

public class Test03_SearchBlob {
    public static void main(String[] args) throws SQLException, ClassNotFoundException, IOException {
        Connection connection = JDBCUtils.getConnection();

        String sql = "SELECT `name`,`photo` from `customers` where `id` = ?;";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setInt(1, 1);

        ResultSet resultSet = preparedStatement.executeQuery();
        // 名字，图片

        if (resultSet.next()) {
            // 获取名字
            String name = resultSet.getString("name");
            System.out.println(name);

            // 获取图片
            Blob photo = resultSet.getBlob("photo");
            InputStream inputStream = photo.getBinaryStream();

            // 把图片通过输出流的方式保存到本地
            FileOutputStream fileOutputStream = new FileOutputStream("file/sunlaoshi.jpg");

            byte[] buffer = new byte[1024];
            int len;

            while ((len = inputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, len);
            }

            // 关闭流操作
            fileOutputStream.close();
            fileOutputStream.close();
        }

        // 关闭数据库操作的连接
        JDBCUtils.closeResource(connection,preparedStatement,resultSet);

    }
}
